var cachedStart = 0
var cachedEnd = 0
var leftHeight = 0.0
var rightHeight = 0.0

var itemsToInsert = []
var itemsToAppend = []

var inserting = false

function onHeightChanged()
{
    inserting = false
    autoInsert()
}

function onModelChanged()
{
    clear()
    if(model)
    {
        distribute()
        if (model.rowsInserted) {
            model.rowsInserted.connect(function (i, start, end) {
                var n = end + 1 - start
                if(start === 0)
                {
                    cachedStart += n
                    cachedEnd += n
                }
                else
                {
                }

                distribute()
            })
        }
    }
}

function clear()
{
    leftModel.clear()
    rightModel.clear()
}

function distribute()
{
    for (var i=0; i < cachedStart; i++)
    {
        itemsToInsert.push(model.get(i))
    }
    cachedStart = 0
    for (cachedEnd; cachedEnd < model.count; cachedEnd++)
    {
        itemsToAppend.push(model.get(cachedEnd))
    }
    if(!inserting)
        autoInsert()
}

function shorterModel()
{
    return leftList.height <= rightList.height ? leftModel : rightModel
}

function autoInsert()
{
    if(itemsToInsert.length)
    {
        var o = itemsToInsert.shift()
        inserting = true
        shorterModel().insert(0, o)
        return
    }
    if(itemsToAppend.length)
    {
        var o = itemsToAppend.shift()
        inserting = true
        shorterModel().append(o)
        return
    }
}
